package com.xiaokang.utils;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.xiaokang.pojo.Bean;

/**
 * 
 * @Description: 单例模式工厂（饿汉式）实现依赖注入
 * @author 小康
 * @version V1.0.0 2019年11月10日 上午8:25:09
 */
public class SingleBeanFactory {
	private static SingleBeanFactory instance = new SingleBeanFactory();
	private Map<String, Object> objMap = new ConcurrentHashMap<String, Object>(0);

	private SingleBeanFactory() {
	}

	public static SingleBeanFactory getInstance() {
		return instance;
	}

	@SuppressWarnings("unchecked")
	public <E> E newInstance(String key) {
		E obj = null;
		if (objMap.containsKey(key)) {
			return (E) objMap.get(key);
		}
		try {
			Bean bean = BaseXML.getBean(key);
			Class<?> cls = Class.forName(bean.getBeanClass());
			obj = (E) cls.newInstance();
			Map<String, String> propertyMap = bean.getPropertyMap();
			for (String perName : propertyMap.keySet()) {
				Field field = cls.getDeclaredField(perName);
				field.setAccessible(true);
				field.set(obj, newInstance(propertyMap.get(perName)));
			}
			objMap.put(key, obj);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}
		return obj;
	}

}
